package omit.wage.controller;

import lombok.extern.slf4j.Slf4j;
import omit.wage.constant.JwtClaimsConstant;
import omit.wage.properties.JwtProperties;
import omit.wage.result.Result;
import omit.wage.utils.JwtUtil;
import omit.wage.dto.AdminLoginDTO;
import omit.wage.entity.Administrator;
import omit.wage.vo.AdminLoginVO;
import omit.wage.service.IAdministratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping
@Slf4j
public class AdminController implements Serializable {
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     *     登录系统的接口实现
     *     参数是 接收前端的密码和账号
     *     返回值是响应 Result
     */
    @PostMapping("/login")
    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO){
        log.info("管理员登录：{}", adminLoginDTO);
        //调用业务层：登录功能
        Administrator loginAdmin = administratorService.login(adminLoginDTO);

        //判断用户是否存在
        if(loginAdmin != null){
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.ADM_ID, loginAdmin.getId());
            claims.put(JwtClaimsConstant.ADM_NAME, loginAdmin.getAccount());
            claims.put(JwtClaimsConstant.ADM_PASSWORD, loginAdmin.getPasswords());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            //封装JWT令牌并传递给前端
            AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                    .token(token)
                    .build();
            return Result.success(adminLoginVO);
        }
        return Result.error("用户名或密码错误");
    }
}
